﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApplicationCache.Interfaces;
using Interfaces.FilterModels;
using Interfaces.Filters;
using Interfaces.Infrastructure;
using Interfaces.Models;
using Interfaces.Providers;

namespace BusinessLogic.Services.HandleStrategy
{
    public class FirstLoadFeedStrategy : IRequestHandleStrategy<IFeed, string, INewsFilter<INewsFilterModel>>
    {
        private INewsDataProvider<IFeed , INewsFilter<INewsFilterModel>> _dataProvider;
        private ICacheManagerWrapper _cacheManager;

        public FirstLoadFeedStrategy(INewsDataProvider<IFeed, INewsFilter<INewsFilterModel>> dataProvider)
        {
            _dataProvider = dataProvider;
            _cacheManager = CacheManagerFactoryWrapper.GetCacheManager();
        }

        public IFeed ProcessRequest(string inputValue, INewsFilter<INewsFilterModel> model)
        {
            //todo we should support get->cached->filter->return chain 
            var feed = _dataProvider.GetData(inputValue, model);

            if (feed != null)
                SaveFeedAsync(inputValue, feed);

            return feed;
        }

        private async void SaveFeedAsync(string key, object value)
        {
            await Task.Factory.StartNew(() => _cacheManager.Add(key, value));
        }
    }  
}
